import { Tabs } from "expo-router";
import React, { useEffect, useState } from "react";
import { Image, StyleSheet, Text, View } from "react-native";
import { Colors } from "@/constants/Colors";
import { useColorScheme } from "@/hooks/useColorScheme";
import { getUserInfoServer, registerServer, updateUserInfoServer } from "@/servers/app-servers";
import { userInfoAtom } from "@/store/user";
import { useAtom } from "jotai";
import Storage from "@/utils/Storage";
import Guide from "@/views/Guide/Guide";

export default function TabLayout() {
	const colorScheme = useColorScheme();
	const [userInfo, setUserInfo] = useAtom(userInfoAtom);
	const [isFirstLaunch, setIsFirstLaunch] = useState<boolean | null>(null);

	// 检查是否有uuid，如果没有则初始化应用
	const checkUuidAndInitApp = async () => {
		try {
			const userInfo = await Storage.getStorage("userInfo");
			if (!userInfo) {
				// 如果没有uuid，执行初始化并显示Guide页面
				console.log("No UUID found, initializing app...");
				await initApp();
				setIsFirstLaunch(true);
			} else {
				// 如果有uuid，直接进入Home页面
				console.log("UUID found, skipping initialization.");
				setUserInfo(JSON.parse(userInfo))
				setIsFirstLaunch(false);
			}
		} catch (error) {
			console.error("Error checking uuid:", error);
		}
	};

	// 初始化应用并注册用户
	const initApp = async () => {
		try {
			const res = await registerServer();
			const {uuid , user_id} = res.data.user_info;
			await Storage.setStorage("uuid", uuid);
            const option = {
				nickname: `Uid${res.data.user_info.user_id}`,
				avatar: `/uploads/api/202405/b3a4b8eaf64d4009f39fdaad0f227bd1.png`,
                result_bg_img:'/uploads/api/202408/6aa5ba70214fb643c81e2c3f37ae9092.png'
			};
            await updateUserInfoServer(option)
            const newRes = await getUserInfoServer(user_id)
			await Storage.setStorage("userInfo", JSON.stringify(newRes.data))
			setUserInfo(newRes.data);
			console.log("App initialized with new UUID:", uuid);
			console.log("userInfo", newRes.data);
		} catch (error) {
			console.error("Error initializing app:", error);
		}
	};

	// 在组件加载时检查uuid
	useEffect(() => {
		checkUuidAndInitApp();
	}, []);

	// 根据isFirstLaunch状态渲染页面
	if (isFirstLaunch === null) {
		// 初始加载状态，可以显示一个加载动画或空白页面
		return null; // 或者返回一个 loading 组件
	}

	// 显示引导页
	if (isFirstLaunch) {
		return <Guide />;
	}

	return (
		<Tabs
			screenOptions={{
				tabBarActiveTintColor: Colors[colorScheme ?? "light"].tint,
				headerShown: false,
			}}
		>
			<Tabs.Screen
				name="index"
				options={{
					title: "首页",
					tabBarIcon: ({ color, focused }) => {
						return (
							<Image
								style={styles.tabImage}
								source={focused ? require("@/assets/tabbar/home-selected.png") : require("@/assets/tabbar/home.png")}
							/>
						)
					},
					tabBarLabel: ({ focused }) => (
						<Text style={[styles.tabText, focused && styles.tabTextFocused]}>首页</Text>
					),	
				}}
			/>
			<Tabs.Screen
				name="work"
				options={{
					title: "作品",
					tabBarIcon: ({ color, focused }) => {
						return (
							<Image
								style={styles.tabImage}
								source={focused ? require("@/assets/tabbar/works-selected.png") : require("@/assets/tabbar/works.png")}
							/>
						)
					},
					tabBarLabel: ({ focused }) => (
						<Text style={[styles.tabText, focused && styles.tabTextFocused]}>作品</Text>
					),
				}}
			/>
			<Tabs.Screen
				name="mine"
				options={{
					title: "我的",
					tabBarIcon: ({ color, focused }) => {
						return (
							<Image
								style={styles.tabImage}
								source={focused ? require("@/assets/tabbar/mine-selected.png") : require("@/assets/tabbar/mine.png")}
							/>
						)
					},
					tabBarLabel: ({ focused }) => (
						<Text style={[styles.tabText, focused && styles.tabTextFocused]}>我的</Text>
					),
				}}
			/>
		</Tabs>
	);
}

const styles = StyleSheet.create({
	tabImage: {
		width: 24,
		height: 24,
	},
	tabText: {
		fontSize: 11,
		color: "#888", // 默认颜色（未选中时）
		fontWeight: "normal",
	},
	tabTextFocused: {
		color: "#000", // 选中时的颜色
		fontWeight: "bold", // 选中时字体加粗
	},
})